/** PROGETTO PRAISED **/
package it.uniroma3.dia.praised.util;

import it.uniroma3.dia.praised.exception.CrawlerException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Collection;

/**
 * Utils :
 * 
 * @author Accosta Augusto
 * @author Lopez Elisabetta
 *
 */
public class Utils {
	
	private static final String DEFAULT_NULL_VALUE = "-";
	private static final int NUM_OF_SIMULATED_CPU = 4;

	/**
	 * This method return the default value in case of <code>null</code> value
	 * 
	 * @param textContent
	 * @return defaultNullValue if textContent is <code>null</code>
	 */
	public static String nullIfDefault(String textContent) {
		return nullIfEqualsTo(DEFAULT_NULL_VALUE, textContent);
	}
	
	/**
	 * This method return the default value in case of <code>null</code> value.
	 * 
	 * @param nullValue
	 * @param textContent
	 * @return
	 */
	public static String nullIfEqualsTo(final String nullValue, String textContent) {
		return textContent.equals(nullValue) ? null : textContent;
	}
	
	/**
	 * This method return the number of available CPU.
	 * 
	 * @return
	 */
	public static int getNumeroCPU() {
		return Runtime.getRuntime().availableProcessors();
	}
	
	/**
	 * This method return the number of available CPU * NUM_OF_SIMULATED_CPU.
	 * 
	 * @return
	 */
	public static int getNumeroCPUSimulate() {
		return Runtime.getRuntime().availableProcessors() * NUM_OF_SIMULATED_CPU;
	}
	
	/**
	 * This method write into a file the list of URL retrieved.
	 * 
	 * @param listaURL - list of extracted URL
	 * @param file
	 * @throws CrawlerException
	 */
	public static void writeIntoFile(File file, Collection<URL> listaURL) throws CrawlerException {

		PrintWriter writer;
		try {
			writer = new PrintWriter(file);
			for (URL url : listaURL) {
				writer.println(url.toString());
			}
			writer.println("N° LINKS: " + listaURL.size());
			
			writer.flush();
			writer.close();
		} catch (FileNotFoundException e) {
			throw new CrawlerException(e);
		}
	}
	

}
